<template>
  <el-dialog
    v-model="dialogVisible"
    :title="subCategoryForm.id ? '编辑子分类' : '新增子分类'"
    width="30%"
  >
    <el-form
      ref="formRef"
      :model="subCategoryForm"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="名称：" prop="name">
        <el-input
          v-model="subCategoryForm.name"
          placeholder="请输入名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类：" prop="categoryId">
        <CategorySelect v-model="subCategoryForm.categoryId" />
      </el-form-item>
      <el-form-item label="图片：" prop="picture">
        <ImgUpload
          @sendImage="sendImage"
          :initialImage="subCategoryForm.picture"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { addSubCategoryAPI, editSubCategoryAPI } from "@/apis/category.js";
import ImgUpload from "@/components/ImageUpload/index.vue";
import CategorySelect from "./CategorySelect.vue";

// 状态和引用定义
const dialogVisible = ref(false);
const formRef = ref(null);
const subCategoryForm = ref({
  name: "",
  picture: "",
  categoryId: "",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "名称为2-10个字符", trigger: "blur" },
  ],
  categoryId: [
    { required: true, message: "分类信息不能为空", trigger: "blur" },
  ],
  picture: [{ required: true, message: "图片不能为空", trigger: "blur" }],
};

// 事件定义
const emit = defineEmits(["success"]);

// 提交表单处理
const onSubmit = async () => {
  await formRef.value.validate();
  const isEdit = subCategoryForm.value.id;
  if (isEdit) {
    await editSubCategoryAPI(subCategoryForm.value);
    ElMessage.success("编辑成功");
  } else {
    await addSubCategoryAPI(subCategoryForm.value);
    ElMessage.success("添加成功");
  }
  dialogVisible.value = false;
  emit("success", isEdit);
};

// 图片上传处理
const sendImage = (url) => {
  subCategoryForm.value.picture = url;
};

// 打开对话框并初始化数据
const open = (row) => {
  dialogVisible.value = true;
  subCategoryForm.value = { ...row };
};

// 暴露方法
defineExpose({
  open,
});
</script>